<template>
  <el-main>
    <el-header>分类管理</el-header>
    <div style="margin: 0.5rem">😽</div>
    <el-row>
      <div class="padding">
        <el-button type="primary" @click="dialogVisible = true"
          >添加分类</el-button
        >
      </div>

      <!-- 添加分类的模态框 -->
      <div>
        <el-dialog
          v-model="dialogVisible"
          title="商品分类"
          width="30%"
          :before-close="handleClose"
        >
          <el-form ref="form" :model="values" status-icon :rules="rules">
            <!-- 上传图片 -->
            <div style="width: 50%; margin: auto">
              🦄
              <input-img class="rounded-inputfull" v-model="values.avatar" />
            </div>
            <el-form-item prop="name" :error="errMsg" style="padding-top: 20px">
              <el-input
                v-model="values.name"
                placeholder="分类名称"
                autocomplete="off"
                size="medium"
                maxlength="100"
                clearable="true"
              ></el-input>
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="addclassify">确定</el-button>
              <el-button type="primary" @click="cancelAddclassify"
                >取消</el-button
              >
            </span>
          </template>
        </el-dialog>
      </div>
    </el-row>
    <div class="padding">
      <el-table
        :data="
          tableData.filter(
            (data) =>
              !search || data.name.toLowerCase().includes(search.toLowerCase())
          )
        "
      >
        <!-- 标题 -->
        <el-table-column align="center" label="图片" prop="picture">
          <template #default="scope">
            <el-image
              style="width: 80px; height: 80px"
              :src="src + scope.row.picture"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column align="center" label="商品类别" prop="name" />
        <el-table-column label="分类有效性" prop="validity" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.validity == 'true' ? 'success' : 'danger'">
              {{ scope.row.validity == "true" ? "有效" : "无效" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center">
          <template #header>
            <el-input
              v-model="search"
              size="mini"
              :suffix-icon="Search"
              placeholder="输入分类名称搜索分类"
            />
          </template>
          <template #default="scope">
            <el-button type="success" size="mini" @click="editShop(scope.row)"
              >修改</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 修改模态框 -->
    <div>
      <el-dialog
        v-model="editClassify"
        title="修改商品分类"
        width="30%"
        :before-close="handleClose"
      >
        <el-form ref="form" :model="editValue" status-icon>
          <!-- 上传图片 -->
          <div style="width: 50%; margin: auto">
            🐑
            <input-img class="rounded-inputfull" v-model="editValue.avatar" />
          </div>
          <el-form-item prop="name" :error="errMsg">
            <el-input
              size="medium"
              v-model="editValue.name"
              placeholder="请输入商品类别"
              style="margin: 10px 0"
              maxlength="100"
            />
            <el-form ref="form" :model="validities" label-width="120px">
              <el-select v-model="editValue.validity" placeholder="有效性">
                <el-option label="有效" value="true"></el-option>
                <el-option label="无效" value="false"></el-option>
              </el-select>
            </el-form>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="editIfy">确定修改</el-button>
            <el-button type="primary" @click="cancelAddclassify"
              >取消</el-button
            >
          </span>
        </template>
      </el-dialog>
    </div>
  </el-main>
</template>

<script>
import { classifyApi, editClassifyApi, addclassifyApi } from "@/api/admin";
import { defineComponent, onBeforeMount, ref, reactive } from "vue";
import InputImg from "@/components/addimg/InputImg.vue";
import { ElMessage } from "element-plus";
import { Search } from "@element-plus/icons-vue";

export default defineComponent({
  components: {
    InputImg,
  },
  setup() {
    const search = ref("");
    let dialogVisible = ref(false);
    const editClassify = ref(false);
    const tableData = reactive([]);
    const src = ref("/avatars/");
    const values = reactive({
      avatar: null,
      name: "",
    });
    const editValue = reactive({
      id: "",
      avatar: null,
      name: "",
      validity: "",
    });
    // 根据分类显示商品
    onBeforeMount(() => {
      classifyApi().then((res) => {
        Object.assign(tableData, res.data.query.result);
      });
    });
    // 添加分类商品
    const addclassify = () => {
      if (values.name == "" || values.avatar == null) {
        ElMessage.error({
          message: "分类名称或图片不能为空！",
        });
      } else {
        const formData = new FormData();
        Object.entries(values).forEach(([k, v]) => {
          if (k == "avatar") {
            if (v) formData.append(k, v, v.name);
          } else formData.append(k, v);
        });
        addclassifyApi(formData).then((res) => {
          if (res.data.success) {
            tableData.push(res.data.classify);
            dialogVisible.value = false;
            ElMessage({
              message: "添加成功",
              type: "success",
            });
            values.name = "";
          } else {
            ElMessage.error({
              message: "不能添加重复的分类名称！",
            });
          }
        });
      }
    };
    // 修改
    const editShop = (row) => {
      editValue.name = row.name;
      editValue.validity = row.validity;
      editValue.id = row.id;
      editValue.avatar = src.value + row.picture;
      editClassify.value = true;
    };
    //确定修改发送
    const editIfy = () => {
      if (editValue.name == "" || editValue.validity == "") {
        ElMessage.error({
          message: "分类名称或有效性不能为空！",
        });
      } else {
        if (typeof editValue.avatar == "object") {
          const formData = new FormData();
          Object.entries(editValue).forEach(([k, v]) => {
            if (k == "avatar") {
              if (v) formData.append(k, v, v.name);
            } else formData.append(k, v);
          });
          editClassifyApi(formData).then((res) => {
            let newData = tableData.map((item) => {
              return item.id == editValue.id ? res.data.classify : item;
            });
            Object.assign(tableData, newData);
          });
        } else {
          let img = editValue.avatar.split("/");
          editValue.avatar = img[img.length - 1];
          editClassifyApi(editValue).then((res) => {
            let newData = tableData.map((item) => {
              return item.id == editValue.id ? res.data.classify : item;
            });
            Object.assign(tableData, newData);
          });
        }
        ElMessage.success("修改成功！");
        editClassify.value = false;
      }
    };
    // 取消发送
    const cancelAddclassify = () => {
      values.name = "";
      dialogVisible.value = false;
      editClassify.value = false;
      editValue.avatar = null;
    };
    // 添加弹出消息框
    return {
      search,
      Search,
      values,
      editValue,
      tableData,
      editClassify,
      dialogVisible,
      editIfy,
      editShop,
      addclassify,
      cancelAddclassify,
      src,
      rules: {
        name: [{ required: true, message: "分类名称不能为空或长度大于100" }],
      },
    };
  },
});
</script>
<style lang="scss" scoped>
.el-header {
  margin-bottom: 0.5rem;
  background-color: #fff;
  padding: 1rem;
  font-size: 2rem;
  font-weight: 900;
}
.el-main {
  border-radius: 10px;
  background-color: #fff;
  min-height: 100vh;
}
.user {
  border-radius: 10px;
  padding: 10px;
  background-color: #fff;
}
.padding {
  padding: 0.5rem;
}
</style>
